package pl.edu.agh.sius.controller;

import javax.faces.application.FacesMessage;

import pl.edu.agh.sius.controller.FirstChoiceBB.Concern;
import pl.edu.agh.sius.model.InputFileData;
import pl.edu.agh.sius.model.TemporaryBenefitRequestBB;
import pl.edu.agh.sius.utils.FacesHelper;
import pl.edu.agh.sius.utils.MailBuilder;
import pl.edu.agh.sius.utils.MailClient;

public class Concern2Controller extends ConcernController{

	private final TemporaryBenefitRequestBB bb = new TemporaryBenefitRequestBB();
	
	public Concern2Controller() {
		super();
		concernTitle = FirstChoiceBB.concernTitles.get(Concern.TEMPORAL_BENEFIT);
		stepTitles = new String[] { "Dane osobowe", "Dokumenty",
				"Zgoda na przetwarzanie danych", "Zatwierdzenie wprowadzonych danych"};
		stepsNo = stepTitles.length;	
	}

	/* miejsce na dodatkową walidacje */
	public String next() {
		if (step == 1
				&& !bb.areAttachementsValid(inputFileController)) {
			FacesHelper.addMessage("Niekompletny zbiór dokumentów.", null);
			return null;
		}
		if (step == 2 && !bb.isAgreement()) {
			FacesHelper.addMessage("Kontynuacja procedury wymaga zgody.", null);
			return null;
		}
		return super.next();
	}

	@Override
	public String submit() {
		try {
			arrangeAttachments();
			MailClient.sendMail(MailBuilder.buildMail(bb, inputFileController), Concern.TEMPORAL_BENEFIT);
			FacesHelper.addMessage("Podanie zostało prawidłowo wysłane.",
					FacesMessage.SEVERITY_INFO);
		} catch (Exception e) {
			e.printStackTrace();
			FacesHelper.addMessage("Podanie nie zostało wysłane. Przyczyna: "
					+ e.getMessage(), FacesMessage.SEVERITY_INFO);
		} finally {
			popupController.setPopup(true);
		}
		return "restart";
	}

	private void arrangeAttachments() {
		for (InputFileData ifd : inputFileController.getFileList()) {
			if (ifd.getFileFormalName().equals(TemporaryBenefitRequestBB.STATEMENT_OF_EARNINGS)) {
				bb.setStatmentOfEarningsFile(ifd.getFileInfo().getFile());
				bb.setStatementOfEarningsDocURL(ifd.getDownloadURL());
			}
			if (ifd.getFileFormalName().equals(TemporaryBenefitRequestBB.TEMPORAL_BENEFIT_PETITION)) {
				bb.setTemporalBenefitPetitionFile(ifd.getFileInfo().getFile());
				bb.setTempBenefitPetitionDocURL(ifd.getDownloadURL());
			}
		}
	}

	public TemporaryBenefitRequestBB getBb() {
		return bb;
	}

}
